<?php

namespace common\components\extenders;

use common\components\helpers\Fun;
use common\components\helpers\Tree;
use common\components\helpers\Util;
use yii\base\BaseObject;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Url;
use doumiaoduo\lhgdialog\LhgDialog;
use yii\web\BadRequestHttpException;

class WebMenuManage extends BaseObject
{

    const TOP_MENU='1'; //顶部导航

    const LEFT_MENU='2'; //左侧导航

//    const CENTER_MENU='3'; //中间导航

    const TOOLBAR='3'; //工具条

    const BATCH_TOOLBAR='4'; //批处理工具条

    const RECORD_ITEM_TOOLBAR='5'; //记录项链接


    public $position;

    public $data;

    public $currentMenu;

    public function __construct($position,$data=[]){
        $this->position=$position;
        $this->data=$data;
        $this->currentMenu=Fun::getWebCurrentMenu(Fun::cache('webmenu_cache'));

    }


    public function create(){
        $menuStr='';
            switch ($this->position) {
                case self::TOP_MENU:
                    $menuStr = $this->topMenu();
                    break;
                case self::LEFT_MENU:
                    $menuStr = $this->leftMenu();
                    break;
//                case self::CENTER_MENU:
//                    $menuStr = '';
//                    break;
                case self::TOOLBAR:
                    $menuStr = $this->Toolbar();
                    break;
                case self::BATCH_TOOLBAR:
                    $menuStr = '';
                    break;
                case self::RECORD_ITEM_TOOLBAR:
                    $menuStr = $this->recordItemToolbar();
                    break;
                default :
                    $menuStr = '';
                    break;
            }
            return $menuStr;
    }


    private function topMenu(){
        Fun::updateCache('webmenu_cache');
        $menuTop=(new Tree(Fun::cache('webmenu_cache')))->get_child(0);
        $toolbar='';
        foreach($menuTop as $v){
            if($v['position']!=self::TOP_MENU)continue;
            if($v['display']!=1)continue;
            if(!self::__procesAccess($v))continue;
            $url=\yii\helpers\Url::to();
            $toolbar.="<li class=\"top_menu\" data-url=\"{$url}\" data-id=\"{$v['id']}\"><a class=\"cursor\" style=\"outline:none;\">{$v['name']}</a></li>";
        }
        return $toolbar;
    }

    private function leftMenu(){
        if(!isset($this->data['parent_id']))return '';
        $tree=new Tree(Fun::cache('webmenu_cache'));
        $menuLeft=$tree->get_child($this->data['parent_id']);
        $menuLeftStr='';
        foreach ($menuLeft as $k=>$v){
            if($v['position']!=self::LEFT_MENU)continue;
            if($v['display']==0)continue;
            if(!self::__procesAccess($v))continue;
            $menuLeftStr.='<h3><span title="展开与收缩" class="cursor"></span>'.$v['name'].'</h3>';
            if($tree->get_child($k)){
                $menuLeftStr.='<ul>';
                foreach ($tree->get_child($k) as $k1=>$v1){
                    if($v1['position']!=self::LEFT_MENU)continue;
                    if($v1['display']==0)continue;
                    if(!self::__procesAccess($v1))continue;
                    $menuLeftUrl=Fun::createMenuUrl($v1);
                    $menuLeftStr.=$v1['display']==5?"<li><a href=\"{$menuLeftUrl}\" target=\"center\" rel=\"iframe_center\">{$v1['name']}</a></li>"
                        :"<li><a href=\"{$menuLeftUrl}\" target=\"main\">{$v1['name']}</a></li>";
                }
                $menuLeftStr.='</ul>';
            }
        }
        return $menuLeftStr;

    }
    private function Toolbar(){
        $menuCache=Fun::cache('webmenu_cache');
        $tree=new Tree($menuCache);
        $menuLevel=$tree->get_level($this->currentMenu['id']);
        $menuList=[];
        if($menuLevel==2){
            $menuList=ArrayHelper::merge([$this->currentMenu['id']=>$this->currentMenu],$tree->get_child($this->currentMenu['id'])?$tree->get_child($this->currentMenu['id']):[]);
        }
        elseif($menuLevel==4){
            $menuList=ArrayHelper::merge([$this->currentMenu['parent_id']=>$menuCache[$this->currentMenu['parent_id']]],$tree->get_pos($this->currentMenu['id']));
        }
        if(empty($menuList))return '';
        $menuDialog=0;
        foreach($menuList as $k=>$v){
            if($v['display']==2||$v['display']==3){
                $menuDialog=$k;
                break;
            }
        }
        if($menuDialog>0){
            $menuDialogArray=$menuList[$menuDialog];
            unset($menuList[$menuDialog]);
            $menuList=ArrayHelper::merge([$menuDialogArray['id']=>$menuDialogArray],$menuList);
        }
        $toolbar=[];
        foreach($menuList as $v){
            if($v['position']==self::RECORD_ITEM_TOOLBAR||$v['position']==self::BATCH_TOOLBAR)continue;
            $toolbar[]=$this->displayMenu($v);
        }

        return !empty($toolbar)?implode(' <span>|</span> ',array_filter($toolbar)):'';
    }

    private function recordItemToolbar(){
        if(empty($this->data)) return '';
        Fun::updateCache('menu_cache');
        $menuCache=Fun::cache('menu_cache');
        $tree=new Tree($menuCache);
        $menuChild=$tree->get_child($this->currentMenu['id']);
        $toolbar=[];
        foreach($menuChild as $v){
            if($v['position']!=self::RECORD_ITEM_TOOLBAR)continue;
            $toolbar[]=$this->displayMenu($v);
        }
        return !empty($toolbar)?implode(' | ',array_filter($toolbar)):'';
    }
    private function  __procesAccess($menu){
                if (\Yii::$app->user->isGuest) {
                   return false;
                }
                elseif (\Yii::$app->user->identity->role != 'admin' && !\Yii::$app->user->can(Fun::getPermissionStr(Fun::cache('menu_cache')[$menu['id']]))) {
                    return false;
                }
                else{
                    return true;
                }
    }
    private function displayMenu($menu){
        switch($menu['display']){
            case 0:
                return null;
            case 1:
                 return ($this->currentMenu['id']==$menu['id'])?Html::a("<em>{$menu['name']}</em>",Fun::createMenuUrl($menu,$this->data),['class'=>'on']):Html::a("<em>{$menu['name']}</em>",Fun::createMenuUrl($menu,$this->data));
            case 2:
                $size=explode('*',$menu['size']);
                 return \doumiaoduo\lhgdialog\LhgDialog::widget([
                'text'=>'<em>'.$menu['name'].'</em>',
                'cssClass'=>'add',
                'dialogOptions'=>[
                    'id'=>'abc',
                    'title'=>$this->getMessage($menu),
                    'width'=>(count($size)>1?$size[0]:'400').'px',
                    'height'=>(count($size)>1?$size[1]:'300').'px',
                    'content'=>'url:'.Fun::createMenuUrl($menu,$this->data),
                    'button'=>"[
                    {name: '提交', callback: function () {
                        top.$(\"iframe[name=abc]\").contents().find(\"#dosubmit\").click();
                        return false;
                    },focus: true},
                    {name: '取消'},
                    ]"
                ]
            ]);
            case 3:
                return '';
            case 4:
                return Html::a($menu['name'],Fun::createMenuUrl($menu,$this->data),[
                    'data'=>[
                        'method'=>'post',
                        'confirm'=>$this->getMessage($menu)
                    ]
                ]);
            default :
                return null;
        }
    }

    private function getMessage($menu){
        if(empty($menu['message'])) return '';
        $message=$menu['message'];
        foreach($this->data as $k=>$v){
            $message=str_replace('{$'.$k.'}',$v,$message);
        }
        return $message;
    }
}